<template>
  <basic-container>
    <el-dialog :append-to-body="true"  :modal="false" :before-close="cancelDialog" :close-on-click-modal="false"
                title="征求意见稿" :visible.sync="dialog" custom-class="ledger" fullscreen top="5vh"
                width="1200px">
      <div class="colums">
        <div class="colums_left">
          <div class="colums_left_middle">
            <div class="middleForm ledger">
              <el-form ref="dataForm" :model="form" class="el-dialog__body" label-width="100px">
                <div class="title">项目信息</div>
                <el-form-item label-width="100px" label="项目名称:" prop="projectName">
                  <el-input v-model="form.projectName" placeholder="项目名称" @focus="showProjectDialog()" :rules="{required: true, message: '项目编号不能为空', trigger: ['focus', 'change']}"></el-input>
                </el-form-item>
                <div class="title">基本信息</div>
                <component :is="auditView" :params="form" :edit="formDisplay"></component>
                <div class="title">审计情况</div>
                <el-row>
                  <el-col>
                    <el-form-item label="基本情况:">
                      <el-input v-model="form.basicInformation" type="textarea"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col>
                    <el-form-item label="审计期间收入支出（费用）情况:">
                      <el-input v-model="form.costsSituation" type="textarea" :autosize="{ minRows: 4}"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col>
                    <el-form-item label="三公经费使用情况:">
                      <el-input v-model="form.costsUseSituation" type="textarea" :autosize="{ minRows: 3}"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col>
                    <el-form-item label="内部管理制度建立及执行情况:">
                      <el-input v-model="form.implementSituation" type="textarea" :autosize="{ minRows: 4}"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col>
                    <el-form-item label="工作业绩:">
                      <el-input v-model="form.workPerformance" type="textarea"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <div class="title">问题记录</div>
                <el-row>
                  <el-col >
                    <el-button icon="el-icon-plus" size="small" type="primary" @click="onAddItem('')">新建</el-button>
                     <el-button icon="el-icon-document-copy" @click="addSelectedRow">复制</el-button>
                    <el-button icon="el-icon-delete" @click="deleteSelectedRows">删除</el-button>
                    <el-button icon="el-icon-delete-solid" @click="clearTableData">删除全部</el-button>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col>
                    <el-table
                      ref="table"
                      :data="tableData"
                      :model="tableData"
                      style="width: 100%"
                      max-height="450"
                      highlight-current-row
                      @selection-change="updateSelectedRows"
                      @current-change="handleCurrentChange"
                    >
                      <el-table-column type="selection" width="55" align="center"></el-table-column>
                      <el-table-column label="序号" width="100">
                        <template #default="{ $index }">
                          <span>{{ $index + 1 }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="问题标题">
                        <template #default="{ row }">
                          <el-input :readonly="formDisplay" v-model="row.problemTitle" type="textarea"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column label="审计发现的主要问题">
                        <template #default="{ row }">
                          <el-input :readonly="formDisplay" v-model="row.problemDesc" type="textarea"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column label="审计意见及建议">
                        <template #default="{ row }">
                          <el-input :readonly="formDisplay" v-model="row.suggestion" type="textarea"></el-input>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-col>
                </el-row>
                <div class="title">征求意见稿</div>
                <el-row>
                  <el-col>
                    <el-form-item label-width="140px" label="征求意见稿:">
                      <web-document :form-data="form" :readWord="formDisplay?'view':'edit'" :pageType="pageType" @createWordFile="wordFileHandle" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button icon="el-icon-close" size="small" @click="cancelDialog">关闭</el-button>
                <el-button icon="el-icon-check" size="small" type="primary" @click="submit" :loading="loading">保存</el-button>
                <el-button icon="el-icon-check" size="small" type="primary" @click="submitAudit" :loading="loading">保存送审</el-button>
              </span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
    <ChoseProject ref="ChoseProject" @setValue="projectDataHandle"/>
  </basic-container>
</template>


<script>
import ChoseProject from "@/components/audited/ChoseProject.vue";
import {submit,getReport,submitAudit} from "@/api/adis/report/reportOpinion";
import {getByProjectId} from "@/api/adis/execute/discover";
import WebDocument from "@/components/form/webDocument.vue";

export default {
  components: {WebDocument, ChoseProject},
  // props: {
  //   dialog: Boolean,
  // },
  dictTypes: ['audit_type_1_sub'],
  data(){
    return{
      isHidden:true,
      dialog: false,
      form:{
        employmentDates:[]
      },
      isView:false,
      tableData:[
        {
          attachmentType : '',
        },
      ],
      selectedRows: [],
      selectedRow: {},
      formDisplay:false,
      pageType:'reportOpinion',
      reportHidden:true,
      auditView: 'ReportAuditType0',
      loading: false,
    }
  },
  watch: {
    // 检测资料清单，如果被全数删除，立即补充一条空的清单
    tableData(newVal){
      if ((!newVal || newVal.length <= 1) && this.tableData.length <= 0){
        const templateData = {
          attachmentType : '',
        };
        this.onAddItem(templateData)
      }
    },
  },
  methods: {
    /**表格处理*/
    onAddItem(val) {
      // 在这里添加添加新项目的逻辑
      if (!this.tableData) this.tableData = []
      this.tableData.push({
        attachmentType: val.attachmentType || '',
        templateId: this.tableData.length + 1,
        name: val.name || '',
        accept: val.accept || '',
        remark: val.remark || '',
      })
    },
    addSelectedRow() {
      if (this.selectedRows.length > 0) {
        this.selectedRows.forEach((selectedRow) => {
          const index = this.tableData.indexOf(selectedRow);
          if (index !== -1) {
            this.onAddItem(selectedRow)
          }
        });
       } else if (Object.keys(this.selectedRow).length !== 0){
        this.onAddItem(this.selectedRow)
      } else {
        this.$message({
          type: "warning",
          message: "请选择一条数据!"
        });
      }
    },
    deleteSelectedRows() {
      if (this.selectedRows.length > 0) {
        this.selectedRows.forEach((selectedRow) => {
          const index = this.tableData.indexOf(selectedRow);
          if (index !== -1) {
            this.tableData.splice(index, 1);
          }
        });
       } else if (Object.keys(this.selectedRow).length !== 0){
        const index = this.tableData.indexOf(this.selectedRow);
        if (index !== -1) {
          this.tableData.splice(index, 1);
        }
      } else {
        this.$message({
          type: "warning",
          message: "请选择一条数据!"
        });
      }
    },
    clearTableData() {
      this.tableData = [];
    },
    updateSelectedRows(selection) {
      this.selectedRows = selection;
    },
    handleCurrentChange(selection){
      this.selectedRow = selection;
    },

    /**项目选择页面*/
    showProjectDialog() {
      this.$refs.ChoseProject.initParams({
        hasNotReport: true ,// 未生成审计报告
        isEngineering: false,
        isTermination: false
      });
    },
    projectDataHandle(row){
      console.log(row.auditType)
      this.projectDialog = false;
      let form = this.form;
      form.auditedUserNames = row.auditedUserNames;
      form.auditTypeSub = row.auditTypeSub;
      form.assistCompanyName = row.assistCompanyName;
      form.auditedCompanyName = row.auditedCompanyName;
      form.projectId = row.projectId;
      form.projectName = row.projectName;
      if (row.tenureStartDate && row.tenureEndDate){
        form.employmentDates=[row.tenureStartDate, row.tenureEndDate];
      }
      this.form = form;
      this.auditView = "ReportAuditType" + row.auditType;
      getByProjectId(row.projectId).then((res)=>{
          this.tableData = res.data.data;
      });
    },
    init(row){
      if (row.reportId){
        getReport(row.reportId).then((res)=>{
          this.form = res.data.data;
          if (this.form.reportType === 0){
            this.form.wordFile = null;
          }
          this.tableData = this.form.projectReportProblems;
          this.form.employmentDates=[this.form.tenureStartDate,this.form.tenureEndDate];
          this.dialog = true;
        })
      }
    },
    cancelDialog(){
      this.dialog = false;
      this.form = {};
      this.clearTableData();
      this.$emit('cancelDialog', {})
    },
    submit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.form.tenureStartDate = this.form.employmentDates[0];
          this.form.tenureEndDate = this.form.employmentDates[1];
          let count = 0
          try{
            this.tableData.forEach((item, i) => {
              if(!item.suggestion){
                this.$message({
                  type: "warning",
                  message: '第' + (i + 1) + "行审计意见及建议不能为空"
                });
                count++
                throw Error();
              }
              if(!item.problemDesc){
                this.$message({
                  type: "warning",
                  message: '第' + (i + 1) + "行审计发现的主要问题不能为空"
                });
                count++
                throw Error();
              }
            })
          }catch(e){
            console.log(e)
          }
          if (count > 0) return
          this.form.projectReportProblems = []
          this.tableData.forEach((item) => {
            this.form.projectReportProblems.push(item);
          })
          this.form.isEngineering = 0;
          this.loading = true;
          submit(this.form).then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.loading = false;
            this.cancelDialog();
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    submitAudit(){
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.form.tenureStartDate = this.form.employmentDates[0];
          this.form.tenureEndDate = this.form.employmentDates[1];
          let count = 0;
          try{
            this.tableData.forEach((item, i) => {
              if(!item.suggestion){
                this.$message({
                  type: "warning",
                  message: '第' + (i + 1) + "行审计意见及建议不能为空"
                });
                count++
                throw Error();
              }
              if(!item.problemDesc){
                this.$message({
                  type: "warning",
                  message: '第' + (i + 1) + "行审计发现的主要问题不能为空"
                });
                count++
                throw Error();
              }
            })
          }catch(e){
            console.log(e)
          }
          if (count > 0) return
          this.form.projectReportProblems = []
          this.tableData.forEach((item) => {
            this.form.projectReportProblems.push(item);
          })
          this.form.isEngineering = 0;
          this.loading = true;
          submitAudit(this.form).then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.loading = false;
            this.cancelDialog();
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    wordFileHandle(e) {
      this.$set(this.form, "wordFile", e.wordFile);
      this.$set(this.form, "reportId", e.id);
      getReport(this.form.reportId).then((res)=>{
        this.form = res.data.data;
        this.tableData = this.form.projectReportProblems;
        this.form.employmentDates=[this.form.tenureStartDate,this.form.tenureEndDate];
        console.log(this.form);
      })
    }
  }
}
</script>
<style>

</style>
